<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Service;

use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsSalesRecord;

class GoodsSalesRecordManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加销量
     * @param array $data
     * @return GoodsSalesRecord
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoodsSalesRecord(array $data)
    {
        $salesRecord = new GoodsSalesRecord();
        $salesRecord->valuesSet($data);

        $this->entityManager->persist($salesRecord);
        $this->entityManager->flush();

        return $salesRecord;
    }

    /**
     * 更改销量
     * @param $salesNum
     * @param $changeType
     * @param $goodsId
     */
    public function changeGoodsSalesNum($salesNum, $changeType, $goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(GoodsSalesRecord::class, 's')->set('s.goodsSalesNum', 's.goodsSalesNum'.$changeType.$salesNum)
            ->where('s.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();
    }

    /**
     * 删除销量
     * @param $goodsId
     */
    public function deleteGoodsSalesRecord($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(GoodsSalesRecord::class, 'r')
            ->where('r.goodsId = :goodsId')->setParameter('goodsId', $goodsId)
            ->andWhere('r.goodsSalesNum = :goodsSalesNum')->setParameter('goodsSalesNum', 0);
        $qb->getQuery()->execute();
    }
}